package com.tg.app.activity.device.add;

import static com.tg.app.activity.device.add.ApSearchDeviceListActivity.getWifiList;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.view.Window;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ListView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;

import com.base.BaseActivity;
import com.inuker.bluetooth.library.ClientManager;
import com.inuker.bluetooth.library.connect.listener.BleConnectStatusListener;
import com.inuker.bluetooth.library.search.SearchResult;
import com.tange.base.toolkit.StringUtils;
import com.tange.module.core.wifi.scan.ApScanConfiguration;
import com.tange.module.core.wifi.scan.BizWiFiUtil;
import com.tange.module.core.wifi.scan.WiFiScanManager;
import com.tg.app.R;
import com.tg.app.adapter.WifiAdapter;
import com.tg.app.bean.WifiItem;
import com.tg.app.helper.ActivityHelper;
import com.tg.app.util.ObjectBoxUtil;
import com.tg.appcommon.android.DeviceAddSoundConstants;
import com.tg.appcommon.android.DialogUtil;
import com.tg.appcommon.android.SoundPlayerManager;
import com.tg.appcommon.android.TGLog;
import com.tg.appcommon.android.TGWifiUtil;
import com.tg.data.helper.DeviceTypeHelper;

import java.util.ArrayList;
import java.util.List;

public class BluetoothDeviceSetWifiActivity extends BaseActivity implements View.OnClickListener {
    public static final String TAG = BluetoothDeviceSetWifiActivity.class.getSimpleName();
    private EditText edtPassword;
    private EditText edtName;
    private ListView listView;
    private final List<WifiItem> wifiList = new ArrayList<>();
    private final List<ScanResult> ApWifiList = new ArrayList<>();
    private WifiAdapter adapter;
    public static final String EXT_UUID = "uuid";
    public static final String EXT_WIFI_UUID = "wifi_uuid";

    public static final String EXT_WIFI_LIST = "wifi_list";
    public static final String EXT_DEVICE_TYPE = "device_type";


    private Button button;
    private ScanResult wifiAp;
    private String mUUID;
    private String mDeviceType;
    Handler handler = new Handler();
    private SearchResult searchResult;

    private final Handler uiHandler = new Handler(Looper.getMainLooper());

    private SoundPlayerManager soundPlayerManager;
    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        TGLog.d("ApSetWifiActivityEx onCreate");
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.fragment_ap_set_wifi_new);
        initView();
        hideActionBar();

        wifiList.clear();
        mUUID = getIntent().getStringExtra(BluetoothDeviceSetWifiActivity.EXT_WIFI_UUID);
        mDeviceType = getIntent().getStringExtra(BluetoothDeviceSetWifiActivity.EXT_DEVICE_TYPE);
        searchResult = getIntent().getParcelableExtra(ApSetWifiActivityEx.EXT_DEVICE_BLUETOOTH);

        adapter = new WifiAdapter(this, wifiList);
        listView.setAdapter(adapter);
        listView.setOnItemClickListener((adapterView, view, i, l) -> {
            AddDeviceReportHelper.onEventClickByName(TAG, "item_" + i);
            wifiAp = ApWifiList.get(i);
            edtName.setText(wifiAp.SSID);
            WifiItem item = wifiList.get(i);
            if (!"null".equals(item.getPassword())) {
                edtPassword.setText(item.getPassword());
            } else {
                edtPassword.setText("");
            }

            listView.setVisibility(View.GONE);

        });

        boolean isLocationGranted = ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
        if (!isLocationGranted) {
            LocationGrantGuideActivity.launch(this);
        } else {
            updateWifiList();
        }

        ClientManager.getClient().registerConnectStatusListener(searchResult.getAddress(), mConnectStatusListener);
    }

    private final BleConnectStatusListener mConnectStatusListener = new BleConnectStatusListener() {
        @Override
        public void onConnectStatusChanged(String mac, int status) {
            TGLog.d(TAG, "mac = " + mac + ", status = " + status);
        }
    };

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == LocationGrantGuideActivity.REQUEST_CODE) {
            if (resultCode == RESULT_CANCELED) {
                finish();
            } else if (resultCode == RESULT_OK) {
                // 刷新WIFI列表
                updateWifiList();
            }
        }
    }

    Runnable timeRunnable = new Runnable() {
        @Override
        public void run() {
            TGLog.d("result =========== = ");
            updateWifiList2();
            handler.postDelayed(this, 1000);
        }
    };

    private void startTimer() {
        handler.postDelayed(timeRunnable, 1000);
    }


    private void updateWifiList() {
        List<ScanResult> list = getIntent().getParcelableArrayListExtra(BluetoothDeviceSetWifiActivity.EXT_WIFI_LIST);
        if (list != null){
            TGLog.d("list ===== " + list.size());
        }
        if (list == null || list.size() == 0) {
            list = getWifiList(getApplicationContext(),  null, false);
        }
        TGLog.i(TAG, "updateWifiList: list = " + list);
        ApWifiList.clear();
        ApWifiList.addAll(list);
        if (list.size() > 0) {
            for (ScanResult result : list) {
                String pwd = ObjectBoxUtil.getPassword(result.SSID);
                TGLog.d("pwd =====" + pwd);
                WifiItem item = new WifiItem(result.SSID, pwd);
                wifiList.add(item);

                if (!StringUtils.isEmpty(pwd)) {
                    String password = edtPassword.getText().toString();
                    if (StringUtils.isEmpty(password)) {
                        if (!"null".equals(pwd)) {
                            edtPassword.setText(pwd);
                        } else {
                            edtPassword.setText("");
                        }
                        edtName.setText(result.SSID);
                        CheckBox box = findViewById(R.id.device_ap_add_checkbox);
                        box.setChecked(true);
                    }
                }
            }
            adapter.notifyDataSetChanged();
        }

        startTimer();
    }

    private boolean isContains(String ssid) {
        for (WifiItem result : wifiList) {
            if (result.uuid.equals(ssid)) {
                return true;
            }
        }
        return false;
    }

    private void updateWifiList2() {
        List<ScanResult> list = getWifiList(getApplicationContext(),  null, false);
        if (list.size() > 0) {
            boolean update = false;
            for (ScanResult result : list) {
                if (!result.SSID.startsWith(ApScanConfiguration.INSTANCE.apNamePrefix()) && !isContains(result.SSID)) {
                    TGLog.d("===result.SSID ======" + result.SSID);
                    ApWifiList.add(result);
                    String pwd = ObjectBoxUtil.getPassword(result.SSID);
                    WifiItem item = new WifiItem(result.SSID, pwd);
                    wifiList.add(item);
                    update = true;
                }
            }
            if (update) {
                adapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    protected void initView() {
        edtName = findViewById(R.id.device_ap_add_set_wifi_name);
        edtPassword = findViewById(R.id.device_ap_add_set_wifi_password);
        listView = findViewById(R.id.device_ap_add_set_wifi_list);
        button = findViewById(R.id.btn_before_add_next);
        button.setOnClickListener(this);
        findViewById(R.id.btn_device_ap_add_more).setOnClickListener(this);
        CheckBox box = findViewById(R.id.device_ap_add_checkbox);
        setListener();
        ActivityHelper.setButtonEnable(button, false);
        box.setChecked(true);
    }

    private void setListener() {
        CheckBox box = findViewById(R.id.device_ap_add_checkbox);
        box.setOnCheckedChangeListener((compoundButton, b) -> {
            AddDeviceReportHelper.onEventClickByName(TAG, "device_ap_add_checkbox");
            if (b) {
                edtPassword.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            } else {
                edtPassword.setTransformationMethod(PasswordTransformationMethod.getInstance());
            }
            String str = edtPassword.getText().toString();
            if (!TextUtils.isEmpty(str)) {
                edtPassword.setSelection(str.length());
            }
        });

        edtPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                updateBtnStatus();

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        edtName.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (wifiAp != null && !TextUtils.equals(wifiAp.SSID, s)) {
                    wifiAp = null;
                }
                if (!TextUtils.isEmpty(s)) {
                    edtName.setSelection(s.length());
                }
                updateBtnStatus();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        findViewById(R.id.back_toolbar).setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.back_toolbar) {
            AddDeviceReportHelper.onEventClickByName(TAG, "back_toolbar");
            onBack();
        } else if (id == R.id.btn_before_add_next) {
            TGLog.d(SelectBluetoothDeviceActivity.TAG, "btn_before_add_next click");
            AddDeviceReportHelper.onEventClickByName(TAG, "btn_before_add_next");
            String name = edtName.getText().toString().trim();
            if (is5GHz(name)) {
                DialogUtil.openDlalog(this,
                        R.string.text_5g_wifi_title,
                        R.string.text_5g_wifi_content,
                        R.string.text_5g_wifi_next,
                        R.string.text_5g_wifi_cancel,
                        v -> {
                            TGLog.d("v id =" + v.getId());
                            AddDeviceReportHelper.onEventClickByName(TAG, "dialog_confirm_btn");
                            goToConnectActivity();
                        },
                        v -> {
                            AddDeviceReportHelper.onEventClickByName(TAG, "dialog_cancel_btn");
                            TGLog.d("v id =" + v.getId());
                        });
            } else {
                goToConnectActivity();
            }
        } else if (id == R.id.btn_device_ap_add_more) {
            AddDeviceReportHelper.onEventClickByName(TAG, "btn_device_ap_add_more");
            if (listView.getVisibility() == View.GONE) {
                listView.setVisibility(View.VISIBLE);
                InputMethodManager manager = ((InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE));
                if (manager != null)
                    manager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            } else {
                listView.setVisibility(View.GONE);
            }
        }
    }

    public boolean is5GHz(int freq) {
        return freq > 4900 && freq < 5900;
    }

    private boolean is5GHz(String ssid) {
        TGLog.d("ssid = " + ssid);
        List<ScanResult> scanResults = TGWifiUtil.noSameName(TGWifiUtil.getWifiScanResult(this));
        for (ScanResult result : scanResults) {
            TGLog.d("result ssid =" + result.SSID + ",result.frequency = " + result.frequency);
            if (result.SSID.equalsIgnoreCase(ssid)) {
                return is5GHz(result.frequency);
            }
        }
        return false;
    }

    private void updateBtnStatus() {
        String name = edtName.getText().toString();
        if (TextUtils.isEmpty(name)) {
            ActivityHelper.setButtonEnable(button, false);
            return;
        }
        if (wifiAp != null) {
            String pwd = edtPassword.getText().toString();
            boolean isEncrypt = isEncrypt();
            if (isEncrypt) {
                if (TextUtils.isEmpty(pwd) || pwd.length() < 8) {
                    ActivityHelper.setButtonEnable(button, false);
                    return;
                }
            }
        }
        ActivityHelper.setButtonEnable(button, true);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (WiFiScanManager.scanner().isLocationEnabled(this)){
            WifiManager mWifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
            if (!mWifiManager.isWifiEnabled()){
                DialogUtil.openWifi(ActivityHelper.getActivityContext(this));
            }else {
                mWifiManager.startScan();
            }
        } else {
            DialogUtil.openGpsService(this);
        }

        playSound();
    }

    private void playSound() {
        if (DeviceTypeHelper.isLockBell(mDeviceType)) {
            return;
        }
        if (soundPlayerManager != null) {
            soundPlayerManager.destroy();
        }
        soundPlayerManager = SoundPlayerManager.create(this);
        uiHandler.postDelayed(() -> {
            if (soundPlayerManager != null) {
                soundPlayerManager.download(DeviceAddSoundConstants.WifiChoose(BluetoothDeviceSetWifiActivity.this), true);
            }
        }, 1000);
    }

    @Override
    protected void onPause() {
        super.onPause();
        pauseSound();
    }

    private void pauseSound() {
        if (DeviceTypeHelper.isLockBell(mDeviceType)) {
            return;
        }
        uiHandler.removeCallbacksAndMessages(null);
        if (soundPlayerManager != null) {
            soundPlayerManager.destroy();
        }
    }

    private boolean isEncrypt() {
        if (wifiAp == null) {
            return false;
        }
        return wifiAp.capabilities.contains("WEP") || wifiAp.capabilities.contains("PSK") || wifiAp.capabilities.contains("EAP");
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        onBack();

    }

    private void onBack() {
        DialogUtil.openDlalog(this,
                R.string.notice_4g_car,
                R.string.confirm_to_add_4g_car,
                R.string.confirm,
                R.string.cancle_add_4g_car,
                v -> {
                    AddDeviceReportHelper.onEventClickByName(TAG, "back_dialog_confirm_btn");
                    BizWiFiUtil.removeDeviceWifi();

                    setResult(0);

                    ActivityHelper.gotoDeviceListPage(BluetoothDeviceSetWifiActivity.this);
                    finish();
                },
                v -> {
                    AddDeviceReportHelper.onEventClickByName(TAG, "back_dialog_confirm_btn");
                    TGLog.d("v id =" + v.getId());
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacks(timeRunnable);
    }



    private void goToConnectActivity() {
        TGLog.d(SelectBluetoothDeviceActivity.TAG,"receiveIOCtrlData" + (System.currentTimeMillis()));

        String name = edtName.getText().toString().trim();
        String pwd = edtPassword.getText().toString();
        TGLog.d(SelectBluetoothDeviceActivity.TAG,"name = " + name + ", pwd = " + pwd);
        ActivityHelper.goToConnectActivity(BluetoothDeviceSetWifiActivity.this, name, pwd, mUUID, "", 0, ApSetWifiActivityEx.EXT_DEVICE_BLUETOOTH, true, searchResult);
    }
}
